package com.xyq.fs.views;

import java.io.BufferedReader;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.lucene.document.Document;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;


import com.xyq.fs.constants.FieldConstant;
import com.xyq.fs.constants.ParseConstant;
import com.xyq.fs.contants.filesuffixes2.ExcelEnums;
import com.xyq.fs.contants.filesuffixes2.PdfEnums;
import com.xyq.fs.contants.filesuffixes2.PptEnums;
import com.xyq.fs.contants.filesuffixes2.TxtEnums;
import com.xyq.fs.contants.filesuffixes2.WordEnums;
import com.xyq.fs.entity.MyFile;
import com.xyq.fs.scan.ScanFileInf;
import com.xyq.fs.search.MySearch;
import com.xyq.fs.search.SearchBody;
import com.xyq.fs.util.FileCodingUtil2;
import com.xyq.fs.util.MyFilesUtil;
import com.xyq.fs.util.MyHighlightUtil;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.InvalidationListener;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;

import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.ImageCursor;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.image.ImageView;
import javafx.scene.control.TableColumn.CellDataFeatures;

import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;

import javafx.scene.text.Text;
import javafx.scene.text.TextFlow;
import javafx.stage.Stage;
import javafx.util.Callback;

/**
 * 查询结果窗口
 * 
 * @author xyq
 *
 */
public class WindowsB extends Application {

	private static ImageCursor Mouse = new ImageCursor(WindowsHelp.getsb(), 0, 0);
	private TableView<MyData> tableView = new TableView<MyData>();

	{
		tableView.setStyle("-fx-font-family: '微软雅黑';");
		tableView.getStylesheets().add(WindwosA.class.getResource("WindowsB.css").toExternalForm());
	}

	private TextFlow tf = new TextFlow();
	private Text t2 = new Text("1");
	// 下一页
	private Button btnNext = new Button("下一页");
	private Button btnPre = new Button("上一页");

	/**
	 * 构建一个查询参数对象
	 */
	private int pageNum = 1;
	private String searchKey = WindwosA.getsearchKeyTextField().getText().replaceAll("\\s+", " ").trim().toLowerCase();
	private String[] searchKeys = searchKey.split(" ");
	private String noSearchKey = WindwosA.getnoSearchTextField().getText().replaceAll("\\s+", " ").trim().toLowerCase();
	private String[] noSearchKeys = noSearchKey.split(" ");
	private SearchBody body = new SearchBody();
	private boolean hasFirst = false;

	{
		body.setPageNum(pageNum);
		body.setNoSearchKeys(noSearchKeys);
		body.setSearchKeys(searchKeys);
		body.setHasFirst(hasFirst);
	}

	// 最大页数
	private int maxPageNum = 0;

	private int totalNum = -1;

	// 分页标记
	private Map<Integer, ScoreDoc> fenyeMap = new HashMap<>();

	// 全局缓存对象
	public static Map<String, MyFile> cacheMyFile = new HashMap<>();

	/**
	 * 构建查询对象
	 */
	private ObservableList<MyData> data = FXCollections.observableArrayList();

	// 绑定文件名
	TableColumn<MyData, TextFlow> nameCol = new TableColumn<MyData, TextFlow>("文件名");
	// 绑定文件预览按钮
	TableColumn<MyData, Button> seeCol = new TableColumn<MyData, Button>("内容预览");
	// 绑定访问目录按钮
	TableColumn<MyData, Button> dirCol = new TableColumn<MyData, Button>("访问目录");
	// 绑定复制文件按钮
	TableColumn<MyData, Button> cpoyCol = new TableColumn<MyData, Button>("复制文件");
	// 绑定笔记文件按钮
	TableColumn<MyData, Button> bzCol = new TableColumn<MyData, Button>("文件笔记");
	Group root = new Group();
	Scene scene = new Scene(root, 758, 550);

	HBox hBox2 = new HBox();
	VBox vBox = new VBox();
	private boolean isShow;
	private Query query = MySearch.buildQuery(body);

	public WindowsB(boolean isShow) {

		tableView.setId("tbv");

		this.isShow = isShow;
	}

	@SuppressWarnings("unchecked")
	@Override
	public void start(Stage primaryStage) throws Exception {

		Platform.runLater(() -> {
			primaryStage.getIcons().add(WindowsHelp.xtb);
			root.getChildren().add(new ImageView(WindowsHelp.tkk));
			root.getChildren().add(vBox);
			vBox.getChildren().addAll(hBox2, tf, tableView);
			VBox.setVgrow(tableView, Priority.ALWAYS);
			tableView.getColumns().addAll(nameCol, seeCol, dirCol, cpoyCol, bzCol);

			vBox.setMinHeight(500);
			vBox.setSpacing(20);

			hBox2.setPadding(new Insets(30, 10, -10, 23));
			hBox2.getChildren().addAll(btnPre, btnNext);

			nameCol.setStyle("-fx-font-family: '微软雅黑';");
			nameCol.setMinWidth(479);
			nameCol.setCellValueFactory(new Callback<CellDataFeatures<MyData, TextFlow>, ObservableValue<TextFlow>>() {
				public ObservableValue<TextFlow> call(CellDataFeatures<MyData, TextFlow> p) {
					return p.getValue().getFileName();
				}
			});

			seeCol.setStyle("-fx-font-family: '微软雅黑';");
			seeCol.setMaxWidth(72);
			seeCol.setMinWidth(72);
			seeCol.setCellValueFactory(new Callback<CellDataFeatures<MyData, Button>, ObservableValue<Button>>() {
				public ObservableValue<Button> call(CellDataFeatures<MyData, Button> p) {
					return p.getValue().getSeeBtn();
				}
			});

			dirCol.setMaxWidth(72);
			dirCol.setMinWidth(72);
			dirCol.setStyle("-fx-font-family: '微软雅黑';");
			dirCol.setCellValueFactory(new Callback<CellDataFeatures<MyData, Button>, ObservableValue<Button>>() {
				public ObservableValue<Button> call(CellDataFeatures<MyData, Button> p) {
					return p.getValue().getDirBtn();
				}
			});

			cpoyCol.setMaxWidth(72);
			cpoyCol.setMinWidth(72);
			cpoyCol.setStyle("-fx-font-family: '微软雅黑';");
			cpoyCol.setCellValueFactory(new Callback<CellDataFeatures<MyData, Button>, ObservableValue<Button>>() {
				public ObservableValue<Button> call(CellDataFeatures<MyData, Button> p) {
					return p.getValue().getCopyBtn();
				}
			});

			bzCol.setMaxWidth(72);
			bzCol.setMinWidth(72);
			bzCol.setStyle("-fx-font-family: '微软雅黑';");
			bzCol.setCellValueFactory(new Callback<CellDataFeatures<MyData, Button>, ObservableValue<Button>>() {
				public ObservableValue<Button> call(CellDataFeatures<MyData, Button> p) {
					return p.getValue().getBzBtn();
				}
			});
			scene.setCursor(Mouse);
			primaryStage.setScene(scene);
			btnNext.setPrefSize(65, 20);
			btnPre.setPrefSize(65, 20);
			primaryStage.setResizable(false);
			primaryStage.setTitle("搜索结果");
			primaryStage.setScene(scene);
			btnNext.getStylesheets().add(WindwosA.class.getResource("WindowsB.css").toExternalForm());
			btnPre.getStylesheets().add(WindwosA.class.getResource("WindowsB.css").toExternalForm());
			tableView.setStyle("-fx-opacity: 0.74;");
			tableView.setMinHeight(400);
			tableView.setTranslateX(0);
			tableView.setItems(data);
			t2.setId("txt");
			t2.setFill(Color.WHITE);
			t2.setFont(new Font("微软雅黑", 15));
			if (isShow)
				primaryStage.show();
		});

		// 在scene中修改光标

		/**
		 * 窗口关闭事件
		 */
		primaryStage.setOnCloseRequest(e -> {

			primaryStage.close();
			data.clear();
			data = null;
			tableView = null;
			System.gc();

		});

		/**
		 * 点击上一页按钮
		 */
		EventHandler<ActionEvent> btnPrePage = new EventHandler<ActionEvent>() {

			@Override
			public void handle(ActionEvent t) {

				Platform.runLater(() -> {
					if (pageNum > 1) {
						pageNum--;
						body.setPageNum(pageNum);
						MyFile my = cacheMyFile.get(searchKey + pageNum + WindwosA.getcomboBox().getValue()
								+ WindwosA.getcomboBox2().getValue() + WindwosA.getCb2().isSelected()
								+ WindwosA.getnoSearchTextField().getText());
						if (my == null) {
							my = MySearch.search(body, query, totalNum, fenyeMap.get(pageNum));
						}

						maxPageNum = my.getMaxPageNum();
						data.clear();
						for (Document doc : my.getDocList()) {
							MyData md = new MyData(doc, searchKeys);
							data.add(md);
						}
						t2.setText(pageNum + "");
					}
				});
			}
		};
		btnPre.setOnAction(btnPrePage);
		/**
		 * 点击下一页按钮
		 */
		EventHandler<ActionEvent> btnNextPage = new EventHandler<ActionEvent>() {
			@Override
			public void handle(ActionEvent t) {

				Platform.runLater(() -> {
					if (pageNum < maxPageNum) {
						pageNum++;
						body.setPageNum(pageNum);
						MyFile my = cacheMyFile.get(searchKey + pageNum + WindwosA.getcomboBox().getValue()
								+ WindwosA.getcomboBox2().getValue() + WindwosA.getCb2().isSelected()
								+ WindwosA.getnoSearchTextField().getText());
						if (my == null) {
							my = MySearch.search(body, query, totalNum, fenyeMap.get(pageNum));
						}
						fenyeMap.put(pageNum + 1, my.getAfterScoreDoc());
						maxPageNum = my.getMaxPageNum();
						data.clear();
						for (Document doc : my.getDocList()) {
							MyData md = new MyData(doc, searchKeys);
							data.add(md);
						}
						t2.setText(pageNum + "");
						// 加入缓存
						WindwosA.getcomboBox();
						cacheMyFile.put(searchKey + pageNum + WindwosA.getcomboBox().getValue()
								+ WindwosA.getcomboBox2().getValue() + WindwosA.getCb2().isSelected()
								+ WindwosA.getnoSearchTextField().getText(), my);

						getNextPage();
					}
				});
			}
		};

		btnNext.setOnAction(btnNextPage);

		/**
		 * 第一次查询
		 */
		Platform.runLater(() -> {

			MyFile my = cacheMyFile
					.get(searchKey + pageNum + WindwosA.getcomboBox().getValue() + WindwosA.getcomboBox2().getValue()
							+ WindwosA.getCb2().isSelected() + WindwosA.getnoSearchTextField().getText());
			if (my == null || ScanFileInf.SCAN_NUM.get() == 1) {
				my = MySearch.search(body, query, totalNum, fenyeMap.get(pageNum));
			}
			fenyeMap.put(pageNum + 1, my.getAfterScoreDoc());
			maxPageNum = my.getMaxPageNum();
			totalNum = my.getTotalResultNum();
			body.setHasFirst(true);
			Text t1 = new Text("关键词:  \"" + searchKey + "\"  查询到了" + (my.getTotalResultNum()) + "条相关记录,每页5条,共"
					+ (my.getMaxPageNum() == 1 ? my.getMaxPageNum() : my.getMaxPageNum()) + "页," + "当前页:");
			t1.setId("txt");
			t1.setFont(new Font("微软雅黑", 15));
			t1.setFill(Color.WHITE);
			tf = new TextFlow(t1, t2);
			tf.setPadding(new Insets(10.5, 17.5, 0, 23));
			for (Document doc : my.getDocList()) {
				MyData md = new MyData(doc, searchKeys);
				data.add(md);
			}
			vBox.getChildren().set(1, tf);

			// 加入缓存
			cacheMyFile.put(searchKey + pageNum + WindwosA.getcomboBox().getValue() + WindwosA.getcomboBox2().getValue()
					+ WindwosA.getCb2().isSelected() + WindwosA.getnoSearchTextField().getText(), my);
			getNextPage();
		});
	}

	private void getNextPage() {

		// 缓存下一页
		new Thread(() -> {
			MyFile my2 = cacheMyFile.get(searchKey + (pageNum + 1) + WindwosA.getcomboBox().getValue()
					+ WindwosA.getcomboBox2().getValue() + WindwosA.getCb2().isSelected());
			if (my2 == null || ScanFileInf.SCAN_NUM.get() == 1) {
				SearchBody body2 = body;
				body2.setPageNum(pageNum + 1);
				my2 = MySearch.search(body2, query, totalNum, fenyeMap.get(body2.getPageNum()));
				cacheMyFile.put(searchKey + body2.getPageNum() + WindwosA.getcomboBox().getValue()
						+ WindwosA.getcomboBox2().getValue() + WindwosA.getCb2().isSelected()
						+ WindwosA.getnoSearchTextField().getText(), my2);
			}
		}).start();
	}

	/**
	 * 页面绑定类
	 * 
	 * @author xyq
	 *
	 */
	class MyData {

		private TextFlow tf;
		private ObservableValue<Button> dirBtn;
		private ObservableValue<Button> copyBtn;
		private ObservableValue<Button> seeBtn;
		private ObservableValue<TextFlow> fileName;
		private String simpleFilePath;
		private ObservableValue<Button> bzBtn;

		public ObservableValue<Button> getBzBtn() {

			return bzBtn;
		}

		public void setBzBtn(ObservableValue<Button> bzBtn) {
			this.bzBtn = bzBtn;
		}

		public MyData(Document doc, String[] keys) {

			this.simpleFilePath = Paths.get(doc.get(FieldConstant.FILE_NAME)).toString();
			this.tf = high(simpleFilePath, keys, doc.get(FieldConstant.FILE_PATH));
			// 行高
			tf.setPrefHeight(68);
			this.fileName = new ObservableValue<TextFlow>() {

				@Override
				public void removeListener(InvalidationListener arg0) {
				}

				@Override
				public void addListener(InvalidationListener arg0) {
				}

				@Override
				public void removeListener(ChangeListener<? super TextFlow> listener) {
				}

				@Override
				public TextFlow getValue() {

					return tf;
				}

				@Override
				public void addListener(ChangeListener<? super TextFlow> listener) {
				}
			};

			// 笔记按钮
			this.bzBtn = new ObservableValue<Button>() {

				@Override
				public void removeListener(InvalidationListener listener) {

				}

				@Override
				public void addListener(InvalidationListener listener) {

				}

				@Override
				public void removeListener(ChangeListener<? super Button> listener) {

				}

				@Override
				public Button getValue() {

					Button btn = new Button("添加笔记");
					if (doc.get(FieldConstant.FILE_BZ_SORT) != null) {
						btn.setText("查看笔记");
						btn.setId("teshu");
						btn.setStyle("-fx-background-color:#97FFFF");
					}

					btn.setOnAction(new EventHandler<ActionEvent>() {

						@Override
						public void handle(ActionEvent event) {
							WindowsD ht = new WindowsD(doc);
							ht.start(new Stage());
						}
					});

					return btn;
				}

				@Override
				public void addListener(ChangeListener<? super Button> listener) {

				}
			};

			this.dirBtn = new ObservableValue<Button>() {
				@Override
				public void addListener(InvalidationListener listener) {
				}

				@Override
				public void removeListener(InvalidationListener listener) {
				}

				@Override
				public void addListener(ChangeListener<? super Button> listener) {
				}

				@Override
				public void removeListener(ChangeListener<? super Button> listener) {
				}

				@Override
				public Button getValue() {
					Button btn = new Button("查看目录");
					btn.setOnAction(new EventHandler<ActionEvent>() {
						@Override
						public void handle(ActionEvent event) {
							Path path = Paths.get(doc.get("FILE_PATH"));
							Path path2 = Paths
									.get(System.getProperty("user.dir") + "\\CONF\\BACKUP\\" + path.getFileName() + "");
							// 0表示原来的，1表示现在的，2表示都没有
							AtomicInteger existType = new AtomicInteger();
							if (!Files.exists(path)) {
								existType.set(1);
								if (!Files.exists(path2)) {
									existType.set(2);
									MyAlert.alertError("文件未找到");
								}
							}
							if (existType.get() != 2) {
								try {
									Runtime.getRuntime()
											.exec("explorer /select, " + (existType.get() == 1 ? path2 : path));
								} catch (IOException e) {
									MyAlert.alertError("文件未找到");
								}
							} else {
								MyAlert.alertError("文件未找到");
							}
						}
					});
					return btn;
				}
			};

			this.seeBtn = new ObservableValue<Button>() {

				@Override
				public void addListener(InvalidationListener listener) {
				}

				@Override
				public void removeListener(InvalidationListener listener) {
				}

				@Override
				public void addListener(ChangeListener<? super Button> listener) {
				}

				@Override
				public void removeListener(ChangeListener<? super Button> listener) {
				}

				@Override
				public Button getValue() {

					Button btn = new Button("内容预览");

					btn.setOnAction(new EventHandler<ActionEvent>() {
						@Override
						public void handle(ActionEvent event) {
							Path path = Paths.get(doc.get(FieldConstant.FILE_PATH));
							Path path2 = Paths
									.get(System.getProperty("user.dir") + "\\CONF\\BACKUP\\" + path.getFileName() + "");
							// 0表示原来的，1表示现在的，2表示都没有
							AtomicInteger existType = new AtomicInteger();
							if (!Files.exists(path)) {
								existType.set(1);

								if (!Files.exists(path2)) {
									existType.set(2);
									MyAlert.alertError("文件未找到");
								}
							}
							if (existType.get() != 2) {
								WindowsC ht = new WindowsC();
								ht.setTitle(path.getFileName().toString());
								// 预览文本文件
								String fname = path.getFileName().toString().toUpperCase();

								if (TxtEnums.suffixContains(fname)) {
									ht.start(new Stage());
									Platform.runLater(new Runnable() {
										@Override
										public void run() {
											String txt = yulanTxt(existType.get() == 1 ? path2 : path, keys)
													.replaceAll("\n+", "<br/>");
											if (txt.length() != 0)
												ht.setText(txt);
										}
									});
								} else if (WordEnums.suffixContains(fname)) {
									ht.start(new Stage());
									Platform.runLater(new Runnable() {
										@Override
										public void run() {
											String txt = yulanWord(existType.get() == 1 ? path2 : path, keys)
													.replaceAll("\n+", "<br/>");
											ht.setText(txt);
										}
									});
								} else if (ExcelEnums.suffixContains(fname)) {
									ht.start(new Stage());
									Platform.runLater(new Runnable() {
										@Override
										public void run() {
											String txt = yulanExcel(existType.get() == 1 ? path2 : path, keys)
													.replaceAll("\n+", "<br/>");
											ht.setText(txt);
										}
									});
								} else if (fname.endsWith(PdfEnums.PDF)) {
									ht.start(new Stage());
									Platform.runLater(new Runnable() {
										@Override
										public void run() {
											String txt = yulanPdf(existType.get() == 1 ? path2 : path, keys)
													.replaceAll("\n+", "<br/>");
											ht.setText(txt);
										}
									});
								} else if (PptEnums.suffixContains(fname)) {
									ht.start(new Stage());
									Platform.runLater(new Runnable() {
										@Override
										public void run() {
											String txt = yulanPpt(existType.get() == 1 ? path2 : path, keys)
													.replaceAll("\n+", "<br/>");
											ht.setText(txt);
										}
									});
								} else {
									MyAlert.alertError("抱歉,非文本文件不可预览");
								}
							}
						}
					});
					return btn;
				}
			};

			this.copyBtn = new ObservableValue<Button>() {
				@Override
				public void removeListener(InvalidationListener listener) {
				}

				@Override
				public void addListener(InvalidationListener listener) {
				}

				@Override
				public void removeListener(ChangeListener<? super Button> listener) {
				}

				@Override
				public Button getValue() {
					Button btn = new Button("复制文件");

					btn.setOnAction(new EventHandler<ActionEvent>() {
						@Override
						public void handle(ActionEvent event) {
							Path path = Paths.get(doc.get("FILE_PATH"));
							Path path2 = Paths
									.get(System.getProperty("user.dir") + "\\CONF\\BACKUP\\" + path.getFileName() + "");
							// 0表示原来的，1表示现在的，2表示都没有
							AtomicInteger existType = new AtomicInteger();
							if (!Files.exists(path)) {
								existType.set(1);

								if (!Files.exists(path2)) {
									existType.set(2);
									MyAlert.alertError("文件未找到");
									return;
								}
							}
							if (existType.get() != 2) {
								try {
									new MyFilesUtil().copeFile((existType.get() == 1 ? path2 : path).toString());
									MyAlert.alert("文件已复制");
									// JOptionPane.showMessageDialog(null,
									// "复制文件成功");
								} catch (Exception e) {
									MyAlert.alertError("文件复制失败");
								}
							} else {
								MyAlert.alertError("文件未找到");
								// MyAlert.alertError("文件未找到");
							}
						}
					});
					return btn;
				}

				@Override
				public void addListener(ChangeListener<? super Button> listener) {

				}
			};

		}

		public ObservableValue<TextFlow> getFileName() {

			return fileName;
		}

		public void setFileName(ObservableValue<TextFlow> fileName) {
			this.fileName = fileName;
		}

		public ObservableValue<Button> getDirBtn() {
			return dirBtn;
		}

		public void setDirBtn(ObservableValue<Button> dirBtn) {
			this.dirBtn = dirBtn;
		}

		public ObservableValue<Button> getCopyBtn() {
			return copyBtn;
		}

		public void setCopyBtn(ObservableValue<Button> copyBtn) {
			this.copyBtn = copyBtn;
		}

		public String getSimpleFilePath() {
			return simpleFilePath;
		}

		public void setSimpleFilePath(String simpleFilePath) {
			this.simpleFilePath = simpleFilePath;
		}

		public TextFlow getTf() {
			return tf;
		}

		public void setTf(TextFlow tf) {
			this.tf = tf;
		}

		public ObservableValue<Button> getSeeBtn() {
			return seeBtn;
		}

		public void setSeeBtn(ObservableValue<Button> seeBtn) {
			this.seeBtn = seeBtn;
		}

	}

	/**
	 * 高亮算法
	 * 
	 * @param str
	 * @param key
	 * @return
	 */
	public static TextFlow high(String str, String[] keys, String path) {

		Set<Character> set = new HashSet<>();
		for (String key : keys) {
			// 关键词转化为小写
			for (int i = 0; i < key.length(); i++)
				set.add(key.charAt(i));
		}
		String str2 = new String(str).toLowerCase();
		List<Text> list = new ArrayList<>();
		int begin = 0;
		int end = 0;
		char c;
		Text t;
		double size = 14;
		for (int i = 0; i < str2.length(); i++) {
			c = str2.charAt(i);
			if (set.contains(c)) {
				// 空白
				if (end - begin > 0 && begin != i) {
					t = new Text(str.substring(begin, end));
					t.setFont(new Font(size));
					list.add(t);
				}
				t = new Text(str.charAt(i) + "");
				t.setFill(Color.RED);
				t.setFont(new Font(size));
				// t.setFont(new Font(17));
				list.add(t);
				begin = i + 1;
			} else {
				end = i + 1;
			}
		}

		if (begin < str.length() - 1)
			list.add(new Text(str.substring(begin)));

		String sb = Paths.get(path).getParent().toString();
		Text tt = new Text("\n" + sb);
		tt.setFont(Font.font("Verdana", FontPosture.ITALIC, 11));
		list.add(tt);
		Text[] tar = {};
		TextFlow tf = new TextFlow(list.toArray(tar));

		tf.getStyleClass().add("copyablelabel");
		list.clear();
		list = null;
		tar = null;
		str2 = null;
		set.clear();
		set = null;
		return tf;
	}

	/**
	 * 预览文件
	 * 
	 * @param path
	 * @param keys
	 * @return
	 */
	public String yulanTxt(Path path, String[] keys) {

		StringBuilder sb = new StringBuilder();
		try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(path.toString()),
				FileCodingUtil2.getCharsetName(path, 1024)));) {
			String str;
			int num = 0;
			while ((str = reader.readLine()) != null) {
				if (str.trim().length() > 0) {

					str = str.replaceAll("<", "< ");
					for (String key : keys) {
						str = MyHighlightUtil.highlight(str, key, "<span style=\"color:red\">", "</span>").trim();
					}
					sb.append(str).append("<br/>");
					num++;
				}
				if (num > 250)
					break;
			}
		} catch (Exception e) {

		}
		return sb.toString();
	}

	/**
	 * 预览文件
	 * 
	 * @param path
	 * @param keys
	 * @return
	 */
	public String yulanWord(Path path, String[] keys) {

		String str = (ParseConstant.iwf.getContent(path));
		for (String key : keys) {
			str = MyHighlightUtil.highlight(str, key, "<span style=\"color:red\">", "</span>");
		}
		return str;
	}

	public String yulanExcel(Path path, String[] keys) {

		String str = (ParseConstant.ief.getContent2(path, null));

		for (String key : keys) {
			str = MyHighlightUtil.highlight(str, key, "<span style=\"color:red\">", "</span>");
		}
		return str;
	}

	public String yulanPdf(Path path, String[] keys) {

		String str;
		try {
			str = (ParseConstant.ipf.getContent(path, 10));
			for (String key : keys) {
				str = MyHighlightUtil.highlight(str, key, "<span style=\"color:red\">", "</span>");
			}
		} catch (EOFException e) {
			str = "文件暂不可预览";
		}
		return str;
	}

	public String yulanPpt(Path path, String[] keys) {

		String str;
		str = (ParseConstant.ippf.getContent(path));
		for (String key : keys) {
			str = MyHighlightUtil.highlight(str, key, "<span style=\"color:red\">", "</span>");
		}
		return str;
	}

}
